<?php


namespace app\back\model;

use PhpOffice\PhpSpreadsheet\Exception as ExcelException;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;
use think\response\Json;
use \Exception;

//use WxPayApi;
//use WxPayConfig;
//use WxPayRefund;

class OrderModel
{
    private static $_table = 'order'; // 订单表
    private static $_goodsLogTable = 'goods_log'; // 商品操作记录表
    private static $_adminTable = 'admin'; // 管理员表
    private static $_orderStatusTable = 'order_status'; // 订单操作记录表
    private static $_drawLogTable = 'draw_log'; // 划账|结算日志
    private static $_companyTable = 'company'; // 公司表

    /**公司获取划账列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getCompanyDrawList($input, $info)
    {
        try {
            if ($info['admin_level'] !== 0) return jsonFail('您没有权限操作');
            $field = 'o.admin_id,a.name,a.phone,sum(if(o.company_status = 1,o.company_price,0)) as is_draw, sum(if(o.company_status = 0,o.company_price,0)) as dis_draw';
            $map = [];
            $map[] = ['o.status', 'in', '-3,-5,5'];
            $map[] = ['o.create_time', '>=', strtotime($input['start'])];
            $map[] = ['o.create_time', '<=', strtotime($input['end'])];
            $map[] = ['o.pay_type', '=', 0];
            if ($input['name'] !== '') {
                $map[] = ['a.name', 'like', "%{$input['name']}%"];
            }
            $table = Db::table(self::$_table)->alias('o')
                ->leftJoin([self::$_adminTable => 'a'], 'a.id = o.admin_id')
                ->where($map)->field($field)->group('o.admin_id');
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('o.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**代理商获取划账列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getAgentDrawList($input, $info)
    {
        try {
            if ($info['admin_level'] !== 1) return jsonFail('您没有权限操作');
            $field = 'o.admin_id,a.name,a.phone,sum(if(o.agent_status = 1,o.primary_price,0)) as is_draw, sum(if(o.agent_status = 0,o.primary_price,0)) as dis_draw';
            $map = [];
            $map[] = ['o.status', 'in', '-3,-5,5'];
            $map[] = ['a.pid', '=', $info['id']];
            $map[] = ['o.create_time', '>=', strtotime($input['start'])];
            $map[] = ['o.create_time', '<=', strtotime($input['end'])];
            $map[] = ['o.pay_type', '=', 0];
            if ($input['name'] !== '') {
                $map[] = ['a.name', 'like', "%{$input['name']}%"];
            }
            $table = Db::table(self::$_table)->alias('o')
                ->leftJoin([self::$_adminTable => 'a'], 'a.id = o.admin_id')
                ->where($map)->field($field)->group('o.admin_id');
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('o.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function list($input, $info)
    {
        try {
            if ($info['admin_level'] !== 2) return jsonFail('您没有权限操作');
            $map[] = ['admin_id', '=', $info['id']];
            $field = 'o.id,o.role_type,o.mastr_order_no,o.order_no,o.is_pay,o.pay_type,o.total_price,o.company_price,o.company_status,o.primary_price,o.agent_status,o.driver_price,o.driver_status,o.status,o.is_pay,o.is_believe,o.beleive_status,o.back_reason,o.back_money,o.unback_reason,o.back_image,o.back_time,o.create_time';
            if ($input['is_believe'] !== '') {
                $map[] = ['o.is_believe', '=', $input['is_believe']];
            }
            if ($input['draw_status'] !== '') {
                $map[] = ['o.driver_status', '=', $input['draw_status']];
            }
            if ($input['status'] !== '') {
                $map[] = ['o.status', '=', $input['status']];
            }
            if ($input['start'] !== '') {
                $map[] = ['o.create_time', '>=', strtotime($input['start'])];
            }
            if ($input['end'] !== '') {
                $map[] = ['o.create_time', '<=', strtotime($input['end'])];
            }

            $table = Db::table(self::$_table)->alias('o')
                ->where($map)->field($field);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => [], 'admin_level' => $info['admin_level']]);
            $list = $table->page($input['page'], $input['limit'])->order('o.create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list, 'admin_level' => $info['admin_level']]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取主订单列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getMasterList($input, $info)
    {
        try {
            if ($info['admin_level'] !== 2) return jsonFail('您没有权限操作');
            $map[] = ['admin_id', '=', $info['id']];
            $field = 'mastr_order_no,from_unixtime(create_time,"%Y-%m-%d %H:%i:%s") as create_time';
            if ($input['start'] !== '') {
                $map[] = ['create_time', '>=', strtotime($input['start'])];
            }
            if ($input['end'] !== '') {
                $map[] = ['create_time', '<=', strtotime($input['end'])];
            }

            $table = Db::table(self::$_table)->where($map)->field($field)->group('mastr_order_no');
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**下载主订单出库excel表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function outExcel($input, $info)
    {
        try {
            $map = [
                ['o.admin_id', '=', $info['id']],
                ['mastr_order_no', '=', $input['mastr_order_no']],
                ['gl.type', '=', 2]
            ];
            // 获取主要信息
            $data = Db::table(self::$_table)->alias('o')
                ->leftJoin([self::$_goodsLogTable => 'gl'], 'o.id = gl.order_id')
                ->where($map)->field('goods_data,weight,o.create_time,group_id,num')->select()->toArray();
            if (!$data) return jsonFail('未找到数据');
            // 获取商家信息
            $storeInfo = Db::table(self::$_companyTable)->field('name')->where('id', $data[0]['group_id'])->find();
            if (!$storeInfo) return jsonFail('未找到数据');
            $dataArr = array_chunk($data, 10);
            $count = count($dataArr);
            $sum = 0;
            $spreadsheet = new Spreadsheet();
            $horizontalCenter = [
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                ],
            ];
            $verticalCenter = [
                'alignment' => [
                    'vertical' => Alignment::VERTICAL_CENTER,
                ],
            ];
            $horizontalLeft = [
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_LEFT,
                ],
            ];
            $horizontalRight = [
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_RIGHT,
                ],
            ];
            $outlineThin = [
                'borders' => [
                    'outline' => [
                        'borderStyle' => Border::BORDER_THIN,
                    ]
                ],
            ];
            $allBordersThin = [
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN,
                    ]
                ],
            ];
            foreach ($dataArr as $k => $v) {
                $sheet = $spreadsheet->createSheet($k);
                //设置工作表标题名称
                $sheet->setTitle('表' . ($k + 1));
                $sheet->getStyle('A1:H18')->applyFromArray($outlineThin);
                $sheet->mergeCells('A1:H1');
                $sheet->setCellValue('A1', '攀枝花市威风商贸出库记录')->getStyle('A1:H1')->applyFromArray($horizontalCenter);
                $sheet->mergeCells('A2:D2');
                $sheet->setCellValue('A2', '收货部门:')->getStyle('A2:D2')->applyFromArray($horizontalLeft);
                $sheet->mergeCells('E2:H2');
                $sheet->setCellValue('E2', '编号:' . $input['mastr_order_no'])->getStyle('E2:H2')->applyFromArray($horizontalLeft);
                $sheet->mergeCells('A3:D3');
                $sheet->setCellValue('A3', '供货单位:' . $storeInfo['name'])->getStyle('A3:D3')->applyFromArray($horizontalLeft);
                $sheet->mergeCells('E3:H3');
                $sheet->setCellValue('E3', '页次:' . $count . '/' . ($k + 1))->getStyle('E2:H2')->applyFromArray($horizontalLeft);
                $sheet->setCellValue('A4', '产品编号')->getStyle('A4')->applyFromArray($outlineThin);
                $sheet->setCellValue('B4', '产品名称')->getStyle('B4')->applyFromArray($outlineThin);
                $sheet->setCellValue('C4', '规格')->getStyle('C4')->applyFromArray($outlineThin);
                $sheet->setCellValue('D4', '价格')->getStyle('D4')->applyFromArray($outlineThin);
                $sheet->setCellValue('E4', '数量')->getStyle('E4')->applyFromArray($outlineThin);
                $sheet->setCellValue('F4', '改重')->getStyle('F4')->applyFromArray($outlineThin);
                $sheet->setCellValue('G4', '金额')->getStyle('G4')->applyFromArray($outlineThin);
                $sheet->setCellValue('H4', '备注')->getStyle('H4')->applyFromArray($outlineThin);
                $inputData = [];
                foreach ($v as $goods) {
                    $goodsData = json_decode($goods['goods_data'], true);
                    $money = $goodsData['price'] * $goods['weight'];
                    $tempData = [
                        str_pad($goodsData['id'], 10, '0', STR_PAD_LEFT),
                        $goodsData['name'],
                        $goodsData['unit_name'],
                        $goodsData['price'],
                        $goods['num'],
                        $goods['weight'],
                        $money
                    ];
                    $sum += $money;
                    $inputData[] = $tempData;
                }
                $sheet->fromArray(
                    $inputData,
                    null,
                    'A5'
                );
                $sheet->getStyle('A5:H16')->applyFromArray($allBordersThin);
                $sheet->mergeCells('A15:C16');
                $sheet->setCellValue('A15', '备注:')->getStyle('A15:C16')->applyFromArray($verticalCenter);
                $sheet->mergeCells('E15:F15');
                $sheet->setCellValue('E15', '合计金额:');
                $sheet->mergeCells('E16:G16');
                $sheet->setCellValue('E16', '金额大写:');
                $sheet->mergeCells('A17:B17');
                $sheet->setCellValue('A17', '收货员:');
                $sheet->mergeCells('C17:H17');
                $sheet->setCellValue('C17', '供应商:');
                $sheet->mergeCells('A18:H18');
//                var_dump($v);exit;
                $sheet->setCellValue('A18', '收货日期:' . date('Y/m/d', strtotime('+1 day', $v[0]['create_time'])))->getStyle('A18')->applyFromArray($horizontalRight);
                $sheet->getColumnDimension('A')->setWidth(12);
                $sheet->getColumnDimension('B')->setWidth(15);
            }
            $sheet->setCellValue('G15', $sum);
            $spreadsheet->setActiveSheetIndex(0);
            $writer = new Xlsx($spreadsheet);
            ob_start(); //打开缓冲区
            $writer->save('php://output');
            $xlsData = ob_get_contents();
            ob_end_clean(); // 清除缓冲
            return jsonSuccess('excl生成成功，进行下载...', "data:application/vnd.ms-excel;base64," . base64_encode($xlsData));
        } catch (ExcelException $e) {
            return jsonFail($e->getMessage());
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取订单日志
     * @param $input
     * @return Json
     */
    public static function getOrderLogList($input)
    {
        try {
            $field = 'change_message,name,phone,role_type,create_time';
            $map = [
                ['oid', '=', $input['id']]
            ];
            $list = Db::table(self::$_orderStatusTable)
                ->where($map)->field($field)->order('create_time', 'asc')->select()->toArray();
            if ($list) return jsonSuccess('获取成功', $list);
            return jsonFail('没有找到任何记录');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }


    /**受理退款
     * @param $input
     * @param $info
     * @return Json
     */
    public static function backMoney($input, $info)
    {
        $flag = false;
        try {
            // 获取订单信息
            $orderInfo = Db::table(self::$_table)->field('mastr_order_no,transaction_id,admin_id,status,total_price,pay_type,is_pay')->where('id', $input['id'])->find();
            if (!$orderInfo) return jsonFail('未找到该订单');
            if ($orderInfo['admin_id'] != $info['id']) return jsonFail('非您管辖的订单无法退款');
            if ($orderInfo['status'] != -1) return jsonFail('非申请退款的订单无法退款');
            if ($orderInfo['is_pay'] != 1) return jsonFail('未支付的订单无法退款');
            if (!in_array($orderInfo['pay_type'], [0, 1, 2])) return jsonFail('未知的支付方式无法退款');
            if ($input['status'] == 0) {
                //拒绝退款
                $map = [
                    ['id', '=', $input['id']],
                    ['admin_id', '=', $info['id']],
                    ['status', '=', -1]
                ];
                $update = [
                    'status' => -5,
                    'unback_reason' => $input['unback_reason']
                ];
                Db::startTrans();
                $flag = true;
                $rtn = Db::table(self::$_table)->where($map)->update($update);
                if ($rtn) {
                    // 添加订单操作记录
                    $insert = [
                        'oid' => $input['id'],
                        'change_message' => "拒绝订单退款，订单总价:{$orderInfo['total_price']}, 拒绝退款理由:{$input['unback_reason']}",
                        'name' => $info['name'],
                        'phone' => $info['phone'],
                        'role_type' => $info['role_name'],
                        'create_time' => time()
                    ];
                    $insertRtn = Db::table(self::$_orderStatusTable)->insert($insert);
                    if ($insertRtn) {
                        return jsonSuccess('操作成功');
                    }
                }
                return jsonFail('操作失败');
            } else {
                //同意退款
                //获取公司反比 代理商反比 司机反比
                $adminPath = explode('-', $info['admin_path']);
                $percentInfo = Db::table(self::$_adminTable)->field('id,level,percent')->where('id', 'in', [$adminPath[2], $adminPath[3], $info['id']])->select()->toArray();
                if (count($percentInfo) != 3) return jsonFail('缺少数据');
                $percentInfo = array_column($percentInfo, null, 'level');
                if ($orderInfo['pay_type'] == 0) {
                    // 微信退款
                    require_once "../sdk/WxpayAPI/lib/WxPay.Config.php";
                    require_once "../sdk/WxpayAPI/lib/WxPay.Api.php";
                    require_once "../sdk/WxpayAPI/example/WxPay.JsApiPay.php";
                    $merchid = \WxPayConfig::MCHID;
                    $params = new \WxPayRefund();
                    $params->SetOut_trade_no($orderInfo['mastr_order_no']);   //自己的订单号
//                    $params->SetTransaction_id($orderInfo['transaction_id']);  //微信官方生成的订单流水号，在支付成功中有返回
                    $params->SetOut_refund_no(create_order_no());   //退款单号
                    $params->SetTotal_fee($orderInfo['total_price'] * 100);   //订单标价金额，单位为分
                    $params->SetRefund_fee($input['back_money'] * 100);   //退款总金额，订单总金额，单位为分，只能为整数
                    $params->SetOp_user_id($merchid);
                    $result = \WxPayApi::refund($params); //退款操作
                    if (($result['return_code'] != 'SUCCESS') || ($result['result_code'] != 'SUCCESS')) {
                        return jsonFail('微信退款失败:' . $result['err_code_des']);
                    }
                    $map = [
                        ['id', '=', $input['id']],
                        ['admin_id', '=', $info['id']],
                        ['status', '=', -1],
                        ['is_pay', '=', 1],
                        ['pay_type', '=', 0]
                    ];
                    Db::startTrans();
                    $flag = true;
                    $rtn = Db::table(self::$_table)->where($map)->update(
                        [
                            'status' => -3,
                            'company_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[0]['percent']} / 100"),
                            'primary_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[1]['percent']} / 100"),
                            'driver_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[2]['percent']} / 100"),
                            'back_money' => Db::raw("`back_money` + {$input['back_money']}"),
                            'back_time' => time()
                        ]
                    );
                    if (!$rtn) {
                        Db::rollback();
                        return jsonFail('微信退款成功,数据重写失败');
                    }
                    // 添加订单操作记录
                    $insert = [
                        'oid' => $input['id'],
                        'change_message' => "同意订单微信退款，订单总价:{$orderInfo['total_price']}, 退款金额:{$input['back_money']}",
                        'name' => $info['name'],
                        'phone' => $info['phone'],
                        'role_type' => $info['role_name'],
                        'create_time' => time()
                    ];
                    $insertRtn = Db::table(self::$_orderStatusTable)->insert($insert);
                    if (!$insertRtn) {
                        Db::rollback();
                        return jsonFail('微信退款成功,数据重写失败');
                    }
                    Db::commit();
                    return jsonSuccess('微信退款成功');
                } else if ($orderInfo['pay_type'] == 1) {
                    // 余额退款
                    $map = [
                        ['id', '=', $input['id']],
                        ['admin_id', '=', $info['id']],
                        ['status', '=', -1],
                        ['is_pay', '=', 1],
                        ['pay_type', '=', 1]
                    ];
                    Db::startTrans();
                    $flag = true;
                    $rtn = Db::table(self::$_table)->where($map)->update(
                        [
                            'status' => -3,
                            'company_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[0]['percent']} / 100"),
                            'primary_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[1]['percent']} / 100"),
                            'driver_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[2]['percent']} / 100"),
                            'back_money' => Db::raw("`back_money` + {$input['back_money']}"),
                            'back_time' => time()
                        ]
                    );
                    if (!$rtn) {
                        Db::rollback();
                        return jsonFail('余额退款失败');
                    }
                    $insert = [
                        'oid' => $input['id'],
                        'change_message' => "同意订单余额退款，订单总价:{$orderInfo['total_price']}, 退款金额:{$input['back_money']}",
                        'name' => $info['name'],
                        'phone' => $info['phone'],
                        'role_type' => $info['role_name'],
                        'create_time' => time()
                    ];
                    $insertRtn = Db::table(self::$_orderStatusTable)->insert($insert);
                    if (!$insertRtn) {
                        Db::rollback();
                        return jsonFail('余额退款失败');
                    }
                    Db::commit();
                    return jsonSuccess('余额退款成功');
                } else {
                    // 授信退款
                    $map = [
                        ['id', '=', $input['id']],
                        ['admin_id', '=', $info['id']],
                        ['status', '=', -1],
                        ['is_pay', '=', 1],
                        ['pay_type', '=', 2]
                    ];
                    Db::startTrans();
                    $flag = true;
                    $rtn = Db::table(self::$_table)->where($map)->update(
                        [
                            'status' => -3,
                            'company_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[0]['percent']} / 100"),
                            'primary_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[1]['percent']} / 100"),
                            'driver_price' => Db::raw("(`total_price` - {$input['back_money']}) * {$percentInfo[2]['percent']} / 100"),
                            'back_money' => Db::raw("`back_money` + {$input['back_money']}"),
                            'back_time' => time()
                        ]
                    );
                    if (!$rtn) {
                        Db::rollback();
                        return jsonFail('授信退款失败');
                    }
                    $insert = [
                        'oid' => $input['id'],
                        'change_message' => "同意订单授信退款，订单总价:{$orderInfo['total_price']}, 退款金额:{$input['back_money']}",
                        'name' => $info['name'],
                        'phone' => $info['phone'],
                        'role_type' => $info['role_name'],
                        'create_time' => time()
                    ];
                    $insertRtn = Db::table(self::$_orderStatusTable)->insert($insert);
                    if (!$insertRtn) {
                        Db::rollback();
                        return jsonFail('授信退款失败');
                    }
                    Db::commit();
                    return jsonSuccess('授信退款成功');
                }
            }
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**运营商获取划账|结算列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getDrawList($input, $info)
    {
        try {
            $map[] = ['o.status', 'in', '-3,-5,5'];
            $map[] = ['o.admin_id', '=', $info['id']];
            $map[] = ['o.create_time', 'between', [strtotime($input['start']), strtotime($input['end'])]];
            switch ($input['type']) {
                case 'drawCompanyVisible': // 获取支付通道划账
                    $map[] = ['o.company_status', '=', 0];
                    $list = Db::table(self::$_table)->alias('o')->field('sum(o.company_price) as money')->where($map)->find();
                    if ($list && $list['money'] !== null) {
                        $list = [$list];
                    } else {
                        $list = [];
                    }
                    break;
                case 'drawAgentVisible': // 获取代理商划账
                    $map[] = ['o.agent_status', '=', 0];
                    $list = Db::table(self::$_table)->alias('o')->field('sum(o.primary_price) as money')->where($map)->find();
                    if ($list && $list['money'] !== null) {
                        $list = [$list];
                    } else {
                        $list = [];
                    }
                    break;
                case 'drawDriverVisible': // 获取司机划账
                    $map[] = ['o.driver_status', '=', 0];
                    if ($input['draw_name'] !== '') {
                        $map[] = ['a.name', 'like', "%{$input['draw_name']}%"];
                    }
                    $list = Db::table(self::$_table)->alias('o')
                        ->leftJoin([self::$_adminTable => 'a'], 'a.id = o.driver_id')
                        ->field('o.driver_id,a.name,a.phone,sum(o.driver_price) as money')->where($map)->group('o.driver_id')->select()->toArray();
                    break;
                case 'settlementVisible': // 获取公司结算
                    $map[] = ['o.beleive_status', '=', 0];
                    $map[] = ['o.is_believe', '=', 1];
                    $map[] = ['o.pay_type', '=', 2];
                    if ($input['draw_name'] !== '') {
                        $map[] = ['c.name', 'like', "%{$input['draw_name']}%"];
                    }
                    $list = Db::table(self::$_table)->alias('o')
                        ->leftJoin([self::$_companyTable => 'c'], 'c.id = o.group_id')
                        ->field('o.group_id,c.name,sum(o.total_price - o.back_money) as money')->where($map)->group('o.group_id')->select()->toArray();
                    break;
            }
            if ($list) return jsonSuccess('获取成功', $list);
            return jsonFail('没有找到任何记录');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**运营商划账|结算订单
     * @param $input
     * @param $info
     * @return Json
     */
    public static function drawOrder($input, $info)
    {
        $flag = false;
        try {
            $map[] = ['o.status', 'in', '-3,-5,5'];
            $map[] = ['o.admin_id', '=', $info['id']];
            $map[] = ['o.create_time', 'between', [strtotime($input['start']), strtotime($input['end'])]];
            switch ($input['type']) {
                case 'drawCompanyVisible': // 支付通道划账
                    $map[] = ['o.company_status', '=', 0];
                    $orderInfo = Db::table(self::$_table)->alias('o')->field('group_concat(o.id) as ids,sum(o.company_price) as money')->where($map)->find();
                    if ($orderInfo['ids'] === null || $orderInfo['money'] === null) return jsonFail('没有可划账的订单');
                    $update = ['company_status' => 1];

                    $data[] = [
                        'desc_name' => '支付通道',
                        'type' => 1,
                        'operate_id' => $info['id'],
                        'name' => $info['name'],
                        'money' => $orderInfo['money'],
                        'draw_time' => "操作时间:{$input['start']}-{$input['end']}",
                        'create_time' => time()
                    ];
                    $ids = $orderInfo['ids'];
                    break;
                case 'drawAgentVisible': // 代理商划账
                    $map[] = ['o.agent_status', '=', 0];
                    $orderInfo = Db::table(self::$_table)->alias('o')->field('group_concat(o.id) as ids,sum(o.primary_price) as money')->where($map)->find();
                    if ($orderInfo['ids'] === null || $orderInfo['money'] === null) return jsonFail('没有可划账的订单');
                    $update = ['agent_status' => 1];
                    $data[] = [
                        'desc_name' => '代理商',
                        'type' => 2,
                        'operate_id' => $info['id'],
                        'name' => $info['name'],
                        'money' => $orderInfo['money'],
                        'draw_time' => "操作时间:{$input['start']}-{$input['end']}",
                        'create_time' => time()
                    ];
                    $ids = $orderInfo['ids'];
                    break;
                case 'drawDriverVisible': // 司机划账
                    $map[] = ['o.driver_id', 'in', $input['id']];
                    $map[] = ['o.driver_status', '=', 0];
                    $orderInfo = Db::table(self::$_table)->alias('o')
                        ->leftJoin([self::$_adminTable => 'a'], 'a.id = o.driver_id')
                        ->field('group_concat(o.id) as ids,sum(o.driver_price) as money,a.name as desc_name')->where($map)->group('o.driver_id')->select()->toArray();
                    $update = ['driver_status' => 1];
                    $data = [];
                    $ids = implode(',', array_column($orderInfo, 'ids'));
                    foreach ($orderInfo as $v) {
                        $data[] = [
                            'desc_name' => $v['desc_name'],
                            'type' => 3,
                            'operate_id' => $info['id'],
                            'name' => $info['name'],
                            'money' => $v['money'],
                            'draw_time' => "操作时间:{$input['start']}-{$input['end']}",
                            'create_time' => time()
                        ];
                    }
                    break;
                case 'settlementVisible': // 公司结算
                    $map[] = ['o.group_id', 'in', $input['id']];
                    $map[] = ['o.beleive_status', '=', 0];
                    $map[] = ['o.is_believe', '=', 1];
                    $map[] = ['o.pay_type', '=', 2];
                    $orderInfo = Db::table(self::$_table)->alias('o')
                        ->leftJoin([self::$_companyTable => 'c'], 'c.id = o.group_id')
                        ->field('group_concat(o.id) as ids,sum(o.total_price - o.back_money) as money,c.name as desc_name')->where($map)->group('o.group_id')->select()->toArray();
                    $update = ['beleive_status' => 1];
                    $data = [];
                    $ids = implode(',', array_column($orderInfo, 'ids'));
                    foreach ($orderInfo as $v) {
                        $data[] = [
                            'desc_name' => $v['desc_name'],
                            'type' => 4,
                            'operate_id' => $info['id'],
                            'name' => $info['name'],
                            'money' => $v['money'],
                            'draw_time' => "操作时间:{$input['start']}-{$input['end']}",
                            'create_time' => time()
                        ];
                    }
                    break;
            }
            Db::startTrans();
            $flag = true;
            $rtn = Db::table(self::$_table)->where('id', 'in', $ids)->update($update);
            if ($rtn != count(explode(',', $ids))) {
                Db::rollback();
                return jsonFail('划账|结算失败，请重试划账|结算');
            }
            // 记录日志
            $rtn = Db::table(self::$_drawLogTable)->insertAll($data);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('划账|结算失败，请重试划账|结算');
            }
            Db::commit();
            return jsonSuccess('划账|结算成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取划账|结算记录
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getDrawLogList($input, $info)
    {
        try {
            $field = 'id,desc_name,money,draw_time,create_time';
            $map = [];
            $map[] = ['operate_id', '=', $info['id']];
            $map[] = ['type', '=', $input['type']];
            if ($input['name'] !== '') {
                $map[] = ['desc_name', 'like', "%{$input['name']}%"];
            }
            $table = Db::table(self::$_drawLogTable)
                ->where($map)->field($field);
            $count = $table->count();
            if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
            $list = $table->page($input['page'], $input['limit'])->order('create_time', 'desc')->select()->toArray();
            return jsonSuccess('获取成功', ['count' => $count, 'list' => $list]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取下单统计列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function getStatisticsList($input, $info)
    {
        $rtn = self::getStatisticsListStatic($input, $info);
        if (!is_array($rtn)) return $rtn;
        return jsonSuccess('获取成功', $rtn);
    }


    /**获取下单统计列表(内部调用)
     * @param $input
     * @param $info
     * @param bool $excel
     * @return Json|array
     */
    public static function getStatisticsListStatic($input, $info, $excel = false)
    {
        try {
            $field = 'c.name as company_name,o.goods_data,sum(o.num) as goods_num,o.group_id';
            $map[] = [
                ['o.admin_id', '=', $info['id']],
                ['o.status', '=', 0],
                ['o.is_pay', '=', 1],
                ['o.create_time', 'between', [strtotime($input['start']), strtotime($input['end'])]]
            ];
            $table = Db::table(self::$_companyTable)->alias('c')
                ->Join([self::$_table => 'o'], 'c.id = o.group_id')
                ->where($map)->group(['o.goods_id', 'o.group_id']);
            if (!$excel) {
                // 页面分页列表
                $count = $table->count();
                if ($count == 0) return jsonSuccess('暂无数据', ['count' => 0, 'list' => []]);
                $table->removeOption('field')->page($input['page'], $input['limit']);
            }
            $list = $table->field($field)->order('o.goods_id')->select()->toArray();
            // 数据整合
            $data = [];
            $total = [];
            foreach ($list as $v) {
                $goodsData = json_decode($v['goods_data'], true);
                $data[] = [
                    'company_name' => $v['company_name'],
                    'goods_name' => $goodsData['name'],
                    'goods_num' => $v['goods_num'],
                    'goods_unit' => $goodsData['unit_name']
                ];
                if ($excel) {
                    if (isset($total[$goodsData['name']])) {
                        $total[$goodsData['name']]['goods_num'] += $v['goods_num'];
                    } else {
                        $total[$goodsData['name']] = [
                            'goods_name' => $goodsData['name'],
                            'goods_num' => $v['goods_num'],
                            'goods_unit' => $goodsData['unit_name']
                        ];
                    }
                }
            }
            if ($excel) {
                return ['list' => $data, 'total' => $total];
            } else {
                return ['count' => $count, 'list' => $data];
            }
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**下载下单统计列表
     * @param $input
     * @param $info
     * @return Json
     */
    public static function statisticsExcel($input, $info)
    {
        try {
            $data = self::getStatisticsListStatic($input, $info, true);
            if (!is_array($data)) return $data;
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
//                //设置工作表标题名称
            $sheet->setTitle('下单');
            $sheet->setCellValue('A1', '公司名称');
            $sheet->getColumnDimension('A')->setWidth(30);
            $sheet->setCellValue('B1', '商品名称');
            $sheet->getColumnDimension('B')->setWidth(30);
            $sheet->setCellValue('C1', '数量');
            $sheet->getColumnDimension('C')->setWidth(20);
            $sheet->fromArray(
                $data['list'],
                null,
                'A2'
            );
            $initNum = 3 + count($data['list']);
            $sheet->setCellValue('A' . $initNum, '商品名称');
            $sheet->setCellValue('B' . $initNum, '数量');
            $sheet->setCellValue('C' . $initNum, '单位');
            $sheet->fromArray(
                $data['total'],
                null,
                'A' . ($initNum + 1)
            );
            $spreadsheet->setActiveSheetIndex(0);
            $writer = new Xlsx($spreadsheet);
            ob_start(); //打开缓冲区
            $writer->save('php://output');
            $xlsData = ob_get_contents();
            ob_end_clean(); // 清除缓冲
            return jsonSuccess('excl生成成功，进行下载...', "data:application/vnd.ms-excel;base64," . base64_encode($xlsData));
        } catch (ExcelException $e) {
            return jsonFail($e->getMessage());
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}